﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;

namespace ResistorMoudel
{
    public partial class Resistor : UserControl
    {
        Form form;
        public ICommunication Resistorserial;
        public bool IsFormShowType = true;


        /// <summary>
        /// 是否可以发送询问心跳信号，默认是true
        /// </summary>
        public bool bAskHeartBeatEnable = true;


        // internal DateTime lastupdatetime = new DateTime();
        bool connectionstatus = false;
        public bool ConnectionStatus
        {
            get
            {
                return connectionstatus;
            }
            set
            {
                if (connectionstatus == value) return;
                connectionstatus = value;
                ConnectionStatusChanged?.Invoke(connectionstatus, EventArgs.Empty);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public new string Name { get; set; }

        public virtual int TestMaxTime { get; }

        public event Action<Resistor, string> ValueReceived;

        public virtual string HeartSendCmd { get; }
        public virtual string StartTestSendCmd { get; }
        public virtual string StopTestSendCmd { get; }
        public virtual string ReadDataSendCmd { get; }

        public virtual string AskTimerCmd { get; }

        public virtual string AskVoltageCmd { get; }

        public virtual string AskLowCmd { get; }

        public virtual string AskUppCmd { get; }

        private static Dictionary<string, Resistor> ResistorCollection = new Dictionary<string, Resistor>();

        public event EventHandler ConnectionStatusChanged;
        internal Resistor()
        {
            InitializeComponent();
        }

        static Resistor()
        {

        }

        public virtual SendBackResult InqueryValues_Timer()
        {
            //测试时间返回值     //"5.0,1\r\n"
            SendBackResult sendBackResult = Resistorserial.SendBackMessageInstant(AskTimerCmd, TestMaxTime);
            if (sendBackResult.Success)
            {
                return SendBackResult.CreateSuccess(sendBackResult.Content);
            }
            else
            {
                return sendBackResult;
            }
        }

        public virtual SendBackResult InqueryValues_Voltage()
        {
            //测试电压返回值     //"100\r\n"
            SendBackResult sendBackResult = Resistorserial.SendBackMessageInstant(AskVoltageCmd, TestMaxTime);
            if (sendBackResult.Success)
            {

                return SendBackResult.CreateSuccess(sendBackResult.Content);

            }
            else
            {
                return sendBackResult;
            }
        }
        public virtual SendBackResult HipotReadParamet(string Order)
        {
            //测试电压返回值     //"100\r\n"
            SendBackResult sendBackResult = Resistorserial.SendBackMessageInstant(Order, TestMaxTime);
            if (sendBackResult.Success)
            {

                return SendBackResult.CreateSuccess(sendBackResult.Content);

            }
            else
            {
                return sendBackResult;
            }
        }
        public virtual SendBackResult HipotSetParameter(string Parameter)
        {
            if (ConnectionStatus)
            {
                Resistorserial.AllReceivedString = "";
                SendBackResult sendBackResult = Resistorserial.SendBackMessageInstant(Parameter, TestMaxTime);
                if (sendBackResult.Content == "OK\r\n")
                {
                    return SendBackResult.CreateSuccess("OK");
                }
            }
            return SendBackResult.CreateSuccess("NG");
        }

        public Resistor(string name, bool isFormShownType,CommunicationType communicationType=CommunicationType.TCP)
        {
            Name = name;
            BeginCtor(name);
            ResistorCollection.Add(name, this);
            InitializeComponent();
            IsFormShowType = isFormShownType;
            switch(communicationType)
            {
                case CommunicationType.TCP:
                    Resistorserial = new NewTCP(name + "_Resistor");
                    break;
                case CommunicationType.UDP:
                    Resistorserial = new NewUDP(name + "_Resistor");
                    break;
                case CommunicationType.SerialPort:
                    Resistorserial = new NewSerialPortWeight(name + "_Resistor");
                    break;
            }

           
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    //下面的TestMaxTime=10000
                    if ((DateTime.Now - Resistorserial.LastDateTime).TotalMilliseconds > TestMaxTime - 2000)
                    {
                        if (bAskHeartBeatEnable == true)
                        {
                            if (Resistorserial.IsOpen && !string.IsNullOrEmpty(HeartSendCmd))
                            {
                                Resistorserial.SendBackMessageInstant(HeartSendCmd, 500);
                            }
                        }
                    }
                    if ((DateTime.Now - Resistorserial.LastDateTime).TotalMilliseconds > 2 * TestMaxTime + 500)
                    {
                        ConnectionStatus = false;
                        Close();
                        Open();
                    }
                    else
                    {
                        ConnectionStatus = true;
                    }
                    Thread.Sleep(500);
                }
            }, TaskCreationOptions.LongRunning);
            EndCtor(name);
        }

        public void Open()
        {
            Resistorserial.Open();
            Resistorserial.OnReceiveData += Resistorserial_OnReceiveData;
        }



        public void Close()
        {
            if (Resistorserial != null)
            {
                if (Resistorserial.IsOpen)
                {
                    Resistorserial.Close();
                }
                Resistorserial.OnReceiveData -= Resistorserial_OnReceiveData;
            }
        }

        internal virtual void Resistorserial_OnReceiveData(string obj)
        {
            //lastupdatetime = DateTime.Now;
            if (ValueReceived != null)
            {
                Task.Factory.StartNew(() =>
                {
                    ValueReceived?.Invoke(this, obj);
                }, TaskCreationOptions.LongRunning);
            }
        }

        public virtual void BeginCtor(string name)
        {


        }

        public virtual void EndCtor(string name)
        {


        }

        public virtual SendBackResult StartTest()
        {
            if (ConnectionStatus)
            {
                Resistorserial.AllReceivedString = "";
                SendBackResult sendBackResult = Resistorserial.SendBackMessageInstant(StartTestSendCmd, TestMaxTime);
                if (sendBackResult.Success)
                {
                    if (sendBackResult.Content != "OK\r\n")
                    {
                        return SendBackResult.CreateFailure(98842, $"{Name}开始测试返回异常值{sendBackResult.Content}");
                    }
                    else
                    {
                        return SendBackResult.CreateSuccess(sendBackResult.Content);
                    }
                }
                else
                {
                    return sendBackResult;
                }
            }
            else
            {
                return SendBackResult.CreateFailure(933, $"{Name}通讯不在线");
            }
        }

        public virtual SendBackResult StopTest()
        {
            if (ConnectionStatus)
            {
                SendBackResult sendBackResult = Resistorserial.SendBackMessageInstant(StopTestSendCmd, TestMaxTime);
                if (sendBackResult.Success)
                {
                    if (sendBackResult.Content != "OK\r\n")
                    {
                        return SendBackResult.CreateFailure(98842, $"{Name}停止测试返回异常值{sendBackResult.Content}");
                    }
                    else
                    {
                        return SendBackResult.CreateSuccess(sendBackResult.Content);
                    }
                }
                else
                {
                    return sendBackResult;
                }
            }
            else
            {
                return SendBackResult.CreateFailure(933, $"{Name}通讯不在线");
            }
        }



        public virtual SendBackResult GetTestResult()
        {
            SendBackResult sendBackResult;
            if (ConnectionStatus)
            {
                sendBackResult = Resistorserial.SendBackMessageInstant(ReadDataSendCmd, TestMaxTime);
            }
            else
            {
                sendBackResult = SendBackResult.CreateFailure(933, $"{Name}通讯不在线");
            }
            return sendBackResult;
        }

        private void FormClosing(object sender, FormClosingEventArgs e)
        {
            form.Controls.Clear();
            timer1.Enabled = false;
        }

        public void FormShow(bool mode)
        {
            if (form != null)
            {
                if (form.IsDisposed)
                {
                    form = null;
                }
                else
                {
                    form.FormClosing += new FormClosingEventHandler(FormClosing);
                    form.Controls.Add(this);
                    timer1.Enabled = true;
                    form.WindowState = FormWindowState.Normal;
                    form.MaximizeBox = false;
                    form.Activate();
                }
            }
            if (form == null)
            {
                form = new Form();
                form.AutoSize = true;
                form.Text = Name;
                form.Size = Size;
                form.FormClosing += new FormClosingEventHandler(FormClosing);
                form.Controls.Add(this);
                timer1.Enabled = true;
            }
            if (mode)
            {
                form.ShowDialog();
            }
            else
            {
                form.Show();
            }
            form.WindowState = FormWindowState.Normal;
            form.MaximizeBox = false;
            form.Activate();
        }

        public void FormShow()
        {
            FormShow(true);
        }


    }


    public enum CommunicationType
    {
        SerialPort,
        TCP,
        UDP
    }
}
